<template>
  <div>

    <div>
      <el-button size="small" plain type="primary" style="margin: 10px" @click="dialogFormVisible = true">新增角色 <i
          class="el-icon-circle-plus"></i></el-button>
      <div style="float: right">
        <el-cascader
            style="margin-left: 10px; width: 255px"
            placeholder="请选择单位"
            ref="dwref"
            v-model="dwid"
            @change=""
            :options="dwoptions"
            :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id', emitPath: false }"
            clearable>
        </el-cascader>
        <el-input style="width: 200px; margin: 0 10px 0 10px" placeholder="请输入角色名" suffix-icon="el-icon-search"
                  v-model="roleName"/>

        <el-button type="primary" @click="search">搜索 <i
            class="el-icon-search"></i></el-button>
      </div>
      <!--      <el-button type="danger" style="margin: 10px" @click="handleDelBatch">批量删除<i-->
      <!--          class="el-icon-remove-outline"></i></el-button>-->

    </div>

    <el-dialog title="新增角色" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="formRules" ref="form">
        <el-form-item label="角色名" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="单位" :label-width="formLabelWidth" prop="dw">
          <el-cascader
              style="width: 255px"
              placeholder="请选择单位"
              ref="dwref"
              v-model="form.dw"
              @change=""
              :options="dwoptions"
              :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id',emitPath: false }"
              clearable></el-cascader>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑角色" :visible.sync="dialogEditFormVisible">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item label="角色名" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="editForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="单位" :label-width="formLabelWidth" prop="dw">
          <el-cascader
              style="width: 255px"
              placeholder="请选择单位"
              ref="dwref"
              v-model="editForm.dw"
              @change=""
              :options="dwoptions"
              :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id',emitPath: false }"
              clearable></el-cascader>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input v-model="editForm.description" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEdit">确 定</el-button>
      </div>
    </el-dialog>
    <!--    default-expanded-keys="[1,2, 3]"-->
    <el-dialog  title="分配菜单" :visible.sync="dialogMenuVisible">
      <!--      <el-checkbox-group v-model="groupsData">-->
      <!--        <el-checkbox v-for="(item,index) in menuGroupdata" :label="item.id" style="width: 200px; padding: 0;margin: 0">-->
      <!--          {{item.name+'SA'}}-->
      <!--        </el-checkbox>-->
      <!--      </el-checkbox-group>-->
      <!--            :default-checked-keys="item.menuRightIds"-->

      <div v-for="(item,index) in menuGroupdata"
           style="display: inline-block;  margin-top: 20px; margin-left: 20px;border-top: 1px solid #7F9DB9; width: 200px; vertical-align: top">
        <el-tag type="info" style="display: block">{{item.name}}</el-tag>
        <el-checkbox :label="item.id" v-model="item.hasRights" :key="index">{{ item.name }}</el-checkbox>
<!--        <el-tag type="info" style="display: block">菜单</el-tag>-->
        <el-tree
            :check-strictly="true"
            :data="item.menuTreeList"
            show-checkbox
            node-key="id"
            ref="tree"
            :default-checked-keys="item.menuRightIds"
            :props="menutreedefaultProps">
        </el-tree>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogMenuVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSetMenuGroup">确 定</el-button>
      </div>
    </el-dialog>

    <el-table :data="tableData" style="margin: 10px; width: 1600px" border stripe>
      <el-table-column label="序号" type="index" width="50">
      </el-table-column>

      <!--      <el-table-column prop="roleId" label="ID" width="300">-->
      <!--      </el-table-column>-->
      <el-table-column prop="roleName" label="角色名" width="200">
      </el-table-column>
      <el-table-column prop="dwObj.dwname" label="单位" width="200">
      </el-table-column>
      <el-table-column prop="description" label="描述" width="800">
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template slot-scope="scope">
          <el-button size="small" plain type="primary" @click="selectMenuGroup(scope.row.roleId)">分配菜单 <i
              class="el-icon-menu"></i>
          </el-button>
          <el-button size="small" plain type="primary" @click="showEditForm(scope.row)">编辑 <i class="el-icon-menu"></i>
          </el-button>
          <!--          <el-button type="primary">编辑<i class="el-icon-edit"></i></el-button>-->
          <!--              <el-button type="danger" slot="reference">删除<i class="el-icon-remove-outline"></i></el-button>-->

          <el-popconfirm
              style="margin: 0 10px"
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="handleDel(scope.row.roleId)"
          >
            <el-button size="small" plain type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i>
            </el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>
    <div class="block" style="padding: 5px">

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
  </div>
</template>
<script>
import service from "@/utils/request";
import ElementUI from "element-ui";

export default {
  created() {
    this.currentUser = JSON.parse(sessionStorage.getItem('user'));
    this.load();
  },
  data() {
    return {
      currentUser:null,
      dwid: null,
      dwoptions: [],
      // tableData: Array(15).fill(item),
      menutreedefaultProps: {
        label: 'name'
      },
      test: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],

      roleId: null,
      menucheckedkeys: null,
      tableData: [],
      pageSize: 10,
      total: 100,
      currentPage: 1,
      roleName: null,
      menudata: [],
      menuGroupdata: [],
      groupsData: [],

      dialogFormVisible: false,
      dialogEditFormVisible: false,
      dialogMenuVisible: false,
      form: {
        roleName: '',
        dw: null,
        description: '',
      },
      editForm: {
        roleId: null,
        roleName: '',
        dw: null,
        description: '',
      },
      formLabelWidth: '120px',
      formRules: {
        roleName: [
          {required: true, message: '请输入角色名', trigger: 'blur'},
        ],
        dw: [
            {required: true, message: '请选择单位', trigger: 'blur'},
        ]
        // password: [
        //   {required: true, message: '请输入密码', trigger: 'blur'},
        //   {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
        // ]
      },
      editFormRules:{
        roleName: [
          {required: true, message: '请输入角色名', trigger: 'blur'},
        ],
        dw: [
          {required: true, message: '请选择单位', trigger: 'blur'},
        ]
      }
    }
  },
  methods: {
    click() {
      console.log(this.menuGroupdata[0].menuRightIds)
      console.log(this.menuGroupdata[1].menuRightIds)
      console.log(this.menuGroupdata[2].menuRightIds)

    },

    load() {
      service.get('/dw/getAll', {}).then(
          response => {
            if (response.data.code == 20000) {
              this.dwoptions = response.data.data
            }
          }
      )
      service.get('/role/getpageWithDw', {
        params: {
          pageSize: this.pageSize,
          pageNum: this.currentPage,
          roleName: this.roleName,
          description: this.description,
          dw: this.dwid,
        }
      }).then(response => {
            if (response.data.code == 20000) {
              this.tableData = response.data.data.records;
              this.total = response.data.data.total;
              this.currentPage = response.data.data.current;
              this.pageSize = response.data.data.size;
            }
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );

    },
    //将部分菜单禁用，禁用需要超级权限的菜单但是用户不是超级用户的菜单
    disableMenus(menutree){
      for(let i=0; i<menutree.length; i++){
        if(menutree[i].children){
          this.disableMenus(menutree[i].children)
        }
        if(menutree[i].needsuper!=null && menutree[i].needsuper==true && (this.currentUser.superadmin ==null || this.currentUser.superadmin==false)){
          // menutree[i].disabled = true
          this.$set(menutree[i], 'disabled', true)
        }else{
          this.$set(menutree[i], 'disabled', false)
        }
      }
    },
    selectMenuGroup(roleId) {
      this.dialogMenuVisible = true;
      this.roleId = roleId
      service.get('/menugroup/getAllWithZRights', {
        params: {
          roleid: roleId
        }
      }).then(
          response => {
            if (response.data.code == 20000) {
              this.menuGroupdata = response.data.data;
              for(let i=0; i<this.menuGroupdata.length; i++){
                // this.$refs.tree[i].setCheckedKeys(this.menuGroupdata[i].menuRightIds)
                this.disableMenus(this.menuGroupdata[i].menuTreeList)
              }
              console.log(this.menuGroupdata)
            } else {
              ElementUI.Message({
                message: response.data.message,
                type: 'error'
              })
            }
          }
      ).catch(error => {
        ElementUI.Message({
          message: error.message,
          type: 'error'
        })
      })

    },
    //将用户有权限的菜单树转换成菜单id列表，其实这里就是如果用户不是超级管理员，就把需要超级权限的菜单排除掉
    menuTreetoList(menuTreeList){
      let menuIds = []
      for(let i=0; i<menuTreeList.length; i++){
        if(menuTreeList[i].disabled == false)//用户有权限才加入
          menuIds.push(menuTreeList[i].id)
        if(menuTreeList[i].children){
          menuIds.push(...this.menuTreetoList(menuTreeList[i].children))
        }
      }
      return menuIds
    },

    handleSetMenuGroup() {

      this.dialogMenuVisible = false
      let params = {
        roleId: this.roleId,
        menuGroupIds:[],
        selmenuIds:[],
        allmenuIds:[],//用户有权限的才加入，也就是如果是超级管理员，则加入所有菜单，如果不是超级管理员就把需要超级权限的菜单排除掉。
      }

      for(let i=0; i<this.menuGroupdata.length; i++){
        if(this.menuGroupdata[i].hasRights){
          params.menuGroupIds.push(this.menuGroupdata[i].id)
        }
        params.selmenuIds.push(...this.$refs.tree[i].getCheckedKeys())
        let allmenuIds = this.menuTreetoList(this.menuGroupdata[i].menuTreeList)
        params.allmenuIds.push(...allmenuIds)
      }

      service.post('/role/setmenugroup/' + this.roleId, params).then(response => {
            if (response.data.code == 20000) {
              this.$message.success("success")
            }
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );

    },
    selectMenu(roleid) {
      this.dialogMenuVisible = true;
      this.roleId = roleid
      service.get('/menu/getlist', {
        // params: {//临时用的分页接口
        //   pageSize: this.pageSize,
        //   pageNum: this.currentPage,
        //
        // }
      }).then(response => {
            if (response.data.code == 20000) {
              this.menudata = response.data.data;
            }
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );

      // service.get('/menu/getpage', {
      //   params: {//临时用的分页接口
      //     pageSize: this.pageSize,
      //     pageNum: this.currentPage,
      //
      //   }
      // }).then(response => {
      //       if (response.data.code == 20000) {
      //         this.menudata = response.data.data.records;
      //       }
      //     },
      //     error => {
      //       ElementUI.Message({
      //         message: error.message,
      //         type: 'error'
      //       })
      //     }
      // );

      service.get('/role/' + this.roleId).then(response => {
            if (response.data.code == 20000) {
              this.menucheckedkeys = response.data.data;
            }
            console.log(this.menucheckedkeys)
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );


    },
    showEditForm(row) {
      this.dialogEditFormVisible = true
      if (row) {
        this.editForm.roleId = row.roleId
        this.editForm.roleName = row.roleName
        this.editForm.dw = row.dw
        this.editForm.description = row.description
      }
    },
    handleEdit() {
      this.$refs.editForm.validate((valid)=>{
        if(!valid){
          return
        }
        service.post('/role/edit', this.editForm).then(response => {
          if (response.data.code == 20000) {
            this.$message.success('success!');
            this.dialogEditFormVisible = false
            this.load()
          } else {
            this.$message.error("error")
            this.dialogEditFormVisible = false
          }
        }).catch(err=>{
          this.$message.error(err.message)
        })
      })


    },


    handleSetMenu() {
      this.dialogMenuVisible = false

      service.post('/role/setmenu/' + this.roleId, this.$refs.tree.getCheckedKeys()).then(response => {
            if (response.data.code == 20000) {
              this.$message.success("success")
            }
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );

    },
    handleSizeChange(val) {
      this.pageSize = val
      this.load()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.load()
    },
    handleSave() {
      this.$refs.form.validate((valid)=>{
        if(!valid){
          return
        }
        service.post('/role', this.form).then(response => {
          if(response.data.code == 20000){
            this.$message.success('success!')
            this.dialogFormVisible = false
            this.load()
          }else{
            this.$message.error(response.data.message)
          }
        }).catch(e=>{
          this.$message.error(e.message)
        })
      })

    },
    handleDel(id) {
      service.delete('/role?id=' + id).then(response => {
        if (response.data.code == 20000) {
          this.$message.success('删除成功!');
          this.load()
        } else {
          this.$message.error(response.data.message);

        }
      })
    },
    search() {
      // if(!this.population.isInteger){  //不能这么判断

      this.currentPage = 1
      this.load()
    },
    handleDelBatch() {
      console.log(this.$route)
      // console.log(this.$router)
    },
    // validatePopulation(){
    //   if(!Number.isInteger(this.population)){
    //     this.$message.info('notInteger')
    //     this.$message.info(this.population)
    //     // this.population = 0
    //   }else{
    //     this.$message.info('isInteger')
    //
    //   }


  }
}
</script>

<style scoped>

</style>
